<?php

/**
 * 中奖统计 每2分运行一次
 *
 * @author fx
 */
require_once dirname(__DIR__) . "/cronBase.php";

use Common\Bridge;
use Notice\Sys;

class offer_1hour extends cronBase
{

    public function doDefault()
    {
        global $argv;
        //计算时间
        $now = date('Y-m-d H:i:00', strtotime('+1 hour'));

        $pdo = Bridge::pdo(Bridge::DB_CENTER_W);
        $select_sql = "SELECT * FROM `Active` WHERE EndTime < '" . $now . "' and `Status` = 1";
        $obj = $pdo->query($select_sql);
        $rs = $obj->fetchAll();
        if (count($rs) > 0) {
            foreach ($rs as $v) {
                debug_log('1Hour_SendNotice:' . [$v]);
              self::send($v);
            }
        }
        $pdo->close();
        Bridge::pdo(Bridge::DB_CENTER_W, 'force_close');
        $pdo = null;
    }

    public static function send($ainfo)
    {
        $pdo = Bridge::pdo(Bridge::DB_CENTER_W);
        $id = $ainfo['Id'];
        $shopinfo = \Center\Shop::getInfoByIds($ainfo['ShopId']);
        $select_sql = "SELECT Status, UserId, OfferPrice FROM `ActiveOffer` WHERE ActiveId=$id";
        $obj = $pdo->query($select_sql);
        $res = $obj->fetchAll();
        $uid = [];
        if (is_array($res) && count($res) > 0) {
            foreach ($res as $v) {
                $uid[$v['UserId']] = $v['UserId'];
                if (count($uid) >= 500) {
                    self::sendNotice($uid, $ainfo, $shopinfo);
                    $uid = [];
                }
            }
            if (count($uid) > 0) {
                self::sendNotice($uid, $ainfo, $shopinfo);
            }
        } else {
            return false;
        }
        return true;
    }

    public static function sendNotice($uid, $ainfo, $shopinfo)
    {
        $msg = '［' . $ainfo['Name'] . '］活动倒计时一小时结束，请留意活动结果公示。';
        $data = [
            'tid' => Sys::TID_MSG_SHOP, // 消息分类ID
            'type' => Sys::TYPE_MSG_ACT_OVER, // 消息类型ID
            'userid' => 0, //用户ID
            'activeid' => $ainfo['Id'], //活动ID
            'shopid' => $shopinfo['ShopId'], //商铺ID
            'cont' => $msg, // 消息内容
            'itemid' => 0, //邀请的用户id等
            'url' => '',
            't' => time()// 时间戳
        ];
        \Notice\Sys::addNotice($uid, 1, $data);
    }
}

$app->run();